﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;
namespace GPMS.Web.Controllers.Filters
{
    using GPMS.Model;
    using GPMS.BLL;
    using System.Web.Routing;

    /// <summary>
    /// 权限验证Attribute
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | 
        AttributeTargets.Method, AllowMultiple = false)]
    public class AuthorizationFilterAttribute : 
        ActionFilterAttribute, IAuthorizationFilter
    {
        #region IAuthorizationFilter 成员
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            //权限无关链接信息
            List<string> noVerify = NoVerify.Get();
            List<string> linkless = NoVerify.GetLinklessController();
            //获取请求中的Controller
            string controller = filterContext.RouteData
                .Values["controller"].ToString().ToLower();
            //获取请求中的Action
            string action = filterContext.RouteData.Values["action"]
                .ToString().ToLower();
            //获取url中一个用于检测权限的标识
            string permimissionCheck = filterContext.HttpContext
                .Request["perchk"];
            //当前登录用户id

            var id = filterContext.HttpContext.User.Identity 
                as FormsIdentity;
            ExtendedGPMSDb gpms = new ExtendedGPMSDb();
            bool permission = false;

            //获取当前请求在数据库中的信息
            ActionInfo actionInfo = actionInfo = gpms.ActionInfos
                    .FirstOrDefault(a => a.IsDeleted == false &&
                        a.ActionName.ToLower().Equals(action) &&
                        a.ControllerInfo.IsDeleted == false &&
                        a.ControllerInfo.ControllerName.ToLower()
                        .Equals(controller));
            //查询权限
            if (id != null && id.IsAuthenticated)
            {
                Guid userId = Guid.Parse(id.Ticket.UserData);
                permission = gpms.ActionInfos
                    .Any(a => a.ActionName.ToLower().Equals(action) &&
                        a.IsDeleted == false &&
                        a.ControllerInfo.ControllerName
                        .ToLower().Equals(controller) &&
                        a.ControllerInfo.IsDeleted == false &&
                        a.Roles
                        .Any(r => r.Users.Any(u => u.UserID == userId)));
            }
            //返回URL权限检测信息
            if (!string.IsNullOrEmpty(permimissionCheck))
            {
                filterContext.Result = new JsonResult()
                {
                    Data = new { permission = permission }
                    //Data = new { permission = true }
                };
                return;
            }
            //无权限验证url返回
            if (controller == "account" || 
                noVerify.Contains(action) || 
                controller == "file" ||
                linkless.Contains(controller))
            {
                return;
            }
            //return;
            //需要权限认证的url验证信息返回
            if (!permission)
            {
                if (actionInfo != null && !string.IsNullOrEmpty(actionInfo.ReturnType))
                {
                    switch (actionInfo.ReturnType.ToLower())
                    {
                        case "FileResult":
                        case "actionresult":
                            filterContext.Result =
                                new RedirectToRouteResult(
                                    new RouteValueDictionary() { 
                                    { "controller", controller }, 
                                    { "action", "Error" }, 
                                    { "msg", "您没有权限访问本地址" } });
                            return;
                        case "jsonresult": filterContext.Result = new JsonResult() { 
                            JsonRequestBehavior = JsonRequestBehavior.AllowGet, 
                            Data = new { error = true } };
                            return;
                    }
                }
                filterContext.Result = new ContentResult()
                {
                    Content = string.Format(
                    "你没有权限访问Controller:{0};Action:{1}",
                        controller,
                        action
                        )
                };
            }
        }
        #endregion
    }
}